<template>
  <div class="register-container">
    <div class="register-card">
      <h1>注册</h1>
      <div v-if="error" class="error-message">
        <p>{{ error }}</p>
        <ul v-if="errorDetails && errorDetails.length">
          <li v-for="(detail, index) in errorDetails" :key="index">{{ detail }}</li>
        </ul>
      </div>
      
      <form @submit.prevent="handleRegister">
        <div class="form-group">
          <label for="username">用户名</label>
          <input 
            type="text" 
            id="username" 
            v-model="username" 
            required 
            placeholder="请输入您的用户名"
          >
          <p v-if="validationErrors.username" class="error-hint">{{ validationErrors.username }}</p>
        </div>
        
        <div class="form-group">
          <label for="email">邮箱</label>
          <input 
            type="email" 
            id="email" 
            v-model="email" 
            required 
            placeholder="请输入您的邮箱"
          >
          <p v-if="validationErrors.email" class="error-hint">{{ validationErrors.email }}</p>
        </div>
        
        <div class="form-group">
          <label for="password">密码</label>
          <input 
            type="password" 
            id="password" 
            v-model="password" 
            required 
            placeholder="请输入您的密码"
          >
          <p v-if="validationErrors.password" class="error-hint">{{ validationErrors.password }}</p>
        </div>
        
        <div class="form-group">
          <label for="confirmPassword">确认密码</label>
          <input 
            type="password" 
            id="confirmPassword" 
            v-model="confirmPassword" 
            required 
            placeholder="请再次输入您的密码"
          >
          <p v-if="passwordMismatch" class="error-hint">两次输入的密码不一致</p>
        </div>
        
        <button 
          type="submit" 
          class="btn-register" 
          :disabled="loading || passwordMismatch"
        >
          {{ loading ? '注册中...' : '注册' }}
        </button>
      </form>
      
      <div class="register-footer">
        <p>已有账号？ <router-link to="/login">立即登录</router-link></p>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, reactive } from 'vue';
import { useRouter } from 'vue-router';
import { useUserStore } from '@/store/user';
import { getUserFriendlyErrorMessage } from '@/utils/errorHandler';

const router = useRouter();
const userStore = useUserStore();

// 表单数据
const username = ref('');
const email = ref('');
const password = ref('');
const confirmPassword = ref('');
const error = ref('');
const errorDetails = ref(null);
const loading = ref(false);
const validationErrors = reactive({
  username: '',
  email: '',
  password: ''
});

// 计算属性：检查密码是否一致
const passwordMismatch = computed(() => {
  return password.value && confirmPassword.value && password.value !== confirmPassword.value;
});

// 清除表单验证错误
const clearValidationErrors = () => {
  validationErrors.username = '';
  validationErrors.email = '';
  validationErrors.password = '';
};

// 验证表单
const validateForm = () => {
  let isValid = true;
  clearValidationErrors();
  
  // 用户名验证
  if (username.value.length < 3) {
    validationErrors.username = '用户名至少需要3个字符';
    isValid = false;
  }
  
  // 邮箱验证
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  if (!emailRegex.test(email.value)) {
    validationErrors.email = '请输入有效的邮箱地址';
    isValid = false;
  }
  
  // 密码验证
  if (password.value.length < 6) {
    validationErrors.password = '密码至少需要6个字符';
    isValid = false;
  }
  
  // 确认密码验证
  if (passwordMismatch.value) {
    error.value = '两次输入的密码不一致';
    isValid = false;
  }
  
  return isValid;
};

// 注册处理
const handleRegister = async () => {
  // 重置错误状态
  error.value = '';
  errorDetails.value = null;
  
  // 验证表单
  if (!validateForm()) {
    return;
  }
  
  loading.value = true;
  
  try {
    const result = await userStore.register({
      username: username.value,
      email: email.value,
      password: password.value
    });
    
    if (result.success) {
      // 注册成功，跳转到首页
      router.push('/');
    } else {
      // 显示错误信息
      error.value = result.error || '注册失败，请稍后再试';
      
      // 处理可能的字段错误
      if (result.details) {
        errorDetails.value = Array.isArray(result.details) 
          ? result.details 
          : Object.values(result.details).flat();
        
        // 设置字段特定的错误
        if (result.details.username) {
          validationErrors.username = result.details.username;
        }
        if (result.details.email) {
          validationErrors.email = result.details.email;
        }
        if (result.details.password) {
          validationErrors.password = result.details.password;
        }
      }
    }
  } catch (err) {
    // 处理异常
    error.value = getUserFriendlyErrorMessage(err) || '注册失败，请稍后再试';
    console.error('Registration error:', err);
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped>
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 80vh;
  padding: 2rem;
}

.register-card {
  width: 100%;
  max-width: 400px;
  padding: 2rem;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  background-color: white;
}

h1 {
  text-align: center;
  margin-bottom: 1.5rem;
  color: #333;
}

.error-message {
  color: #ff3860;
  background-color: #feecf0;
  padding: 0.75rem;
  border-radius: 4px;
  margin-bottom: 1.5rem;
  font-size: 0.9rem;
}

.error-message ul {
  margin-top: 0.5rem;
  margin-bottom: 0;
  padding-left: 1.5rem;
}

.error-hint {
  color: #ff3860;
  font-size: 0.8rem;
  margin-top: 0.25rem;
  margin-bottom: 0;
}

.form-group {
  margin-bottom: 1.5rem;
}

label {
  display: block;
  margin-bottom: 0.5rem;
  font-weight: 500;
}

input {
  width: 100%;
  padding: 0.75rem;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 1rem;
}

input:focus {
  outline: none;
  border-color: #4CAF50;
  box-shadow: 0 0 0 2px rgba(76, 175, 80, 0.2);
}

.btn-register {
  width: 100%;
  padding: 0.75rem;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 1rem;
  font-weight: 600;
  cursor: pointer;
  transition: background-color 0.3s;
}

.btn-register:hover {
  background-color: #45a049;
}

.btn-register:disabled {
  background-color: #9e9e9e;
  cursor: not-allowed;
}

.register-footer {
  margin-top: 1.5rem;
  text-align: center;
}

.register-footer a {
  color: #4CAF50;
  text-decoration: none;
}

.register-footer a:hover {
  text-decoration: underline;
}

/* 响应式调整 */
@media (max-width: 480px) {
  .register-card {
    padding: 1.5rem;
  }
}
</style> 